// <editor-fold defaultstate="collapsed" desc="GNU GPLv3 Header">
/*
 * File:   SimpleRead.java
 *
 * Copyright (C) 2013 Robert Antoni Buj Gelonch <rbuj@uoc.edu>
 * Copyright (C) 2013 David Megias Jimenez <dmegias@uoc.edu>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="imports">
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
// </editor-fold>

/**
 *
 * @author Robert Antoni Buj Gelonch <rbuj@uoc.edu>
 */
public class SimpleRead implements SerialPortEventListener {

    static CommPortIdentifier portId;
    static Enumeration portList;
    SerialPort serialPort = null;
    InputStream inputStream;
    OutputStream outputStream;
    Thread readThread;
    private byte[] buffer = new byte[1024];

    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.print("java -jar Explorer16dsPIC33F_uart2.jar /dev/tty.usbserial\n");
            System.exit(-1);
        }
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals(args[0])) {
                    if (portId.isCurrentlyOwned()) {
                        System.out.println("Error: Port is currently in use");
                    } else {

                        SimpleRead reader = new SimpleRead();
                    }
                }
            }
        }
    }

    /**
     *
     */
    public SimpleRead() {
        try {
            serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
        } catch (PortInUseException e) {
            Logger.getLogger(SimpleRead.class.getName()).log(Level.SEVERE, null, e);

        }
        try {
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
        } catch (IOException e) {
            Logger.getLogger(SimpleRead.class.getName()).log(Level.SEVERE, null, e);
        }
        try {
            serialPort.addEventListener(this);
        } catch (TooManyListenersException e) {
            Logger.getLogger(SimpleRead.class.getName()).log(Level.SEVERE, null, e);
        }
        serialPort.notifyOnDataAvailable(true);
        try {
            serialPort.setSerialPortParams(230400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
            Logger.getLogger(SimpleRead.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    /**
     *
     * @param spe
     */
    @Override
    public void serialEvent(SerialPortEvent spe) {
        switch (spe.getEventType()) {
            case SerialPortEvent.BI:
                System.out.print("BI\n");
            case SerialPortEvent.OE:
                System.out.print("OE\n");
            case SerialPortEvent.FE:
                System.out.print("FE\n");
            case SerialPortEvent.PE:
                System.out.print("PE\n");
            case SerialPortEvent.CD:
                System.out.print("CD\n");
            case SerialPortEvent.CTS:
                System.out.print("CTS\n");
            case SerialPortEvent.DSR:
                System.out.print("DSR\n");
            case SerialPortEvent.RI:
                System.out.print("RI\n");
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                System.out.print("Out Buff Empty\n");
                break;
            case SerialPortEvent.DATA_AVAILABLE:
                int data;
                int len = 0;
                try {
                    while ((data = inputStream.read()) > -1) {
                        if (data == '\n') {
                            break;
                        }
                        buffer[len++] = (byte) data;
                    }
                    System.out.print(new String(buffer, 0, len) + "\n");
                } catch (IOException ex) {
                    Logger.getLogger(SimpleRead.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
        }
    }
}
